<?php

namespace App\Jobs;

use App\Models\AutoAddOrderLog;
use App\Models\BookRule;
use App\Models\Child;
use App\Models\User;
use App\Services\BookOrderService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;

class AutomaticOrdering implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $bookRule;

    /**
     *
     * Create a new job instance.
     *
     * AutomaticOrdering constructor.
     * @param $bookRule
     */
    public function __construct(BookRule $bookRule)
    {
        $this->bookRule = $bookRule;
    }

    /**
     * @throws \Exception
     * 根据订餐规则加单
     */
    public function handle()
    {
        $startTime = microtime(true);

        $count = 0;
        $bookRule = $this->bookRule;
        // 新增订餐规则成功时，为能够订到当前订餐规则，并且为自动订餐的所有用户新增一条订单记录
        // 自动订餐的用户
        $users = $bookRule->getUsersByRule();
        foreach ($users as $user) {
            DB::beginTransaction();
            try {
                // 给自动订餐的用户加单
                if ($user->canBookByRule($bookRule)) {
                    if (BookOrderService::generateAutoOrder($user, $bookRule)) {
                        $count++;
                    }
                }
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                throw $exception;
            }
        }

        // 当前订餐规则下的学校的用户
        $schoolUsers = User::query()->where('school_id', $bookRule->school_id)->where('status', User::ACTIVE)->get();
        foreach ($schoolUsers as $user) {
            DB::beginTransaction();
            try {
                // 给当前用户下开启自动订餐的子女加单
                $children = $bookRule->getChildrenByRule($user);
                foreach ($children as $child) {
                    if ($user->canBookByRule($bookRule, $child->id)) {
                        if (BookOrderService::generateAutoChildrenOrder($user, $bookRule, $child->id)) {
                            $count++;
                        }
                    }
                }
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
                throw $exception;
            }
        }

        $endTime = microtime(true);

        // 添加生成订单记录
        $autoAddOrderLog = new AutoAddOrderLog();
        $autoAddOrderLog->book_rule_id = $bookRule->id;
        $autoAddOrderLog->count = $count;
        $autoAddOrderLog->excute_time = round($endTime - $startTime, 3);
        $autoAddOrderLog->save();
    }
}
